<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    @ok="handleSubmit"
    title="编辑属性"
    :destroyOnClose="true"
    :closeFunc="close"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
  >
    <Row :gutter="12">
      <Col span="10"><span>属性名称</span></Col>
      <Col span="10"><span>属性值</span></Col>
    </Row>
    <p v-show="!p.length" class="mt-24px text-lg text-center">没有设置属性</p>
    <Form :model="p" ref="pForm">
      <Row v-for="(data, index) in p" :key="data.key" class="flex items-center" :gutter="12">
        <Col span="10">
          <FormItem :name="[index, 'key']" required>
            <Select
              v-model:value="data.key"
              :disabled="isDisable"
              v-if="editData.edit.level != 3"
              placeholder="请选择"
            >
              <SelectOption
                v-for="item in option"
                :key="item.value"
                :disabled="isSelectedByOthers(item.value, data.key)"
                >{{ item.label }}</SelectOption
              >
            </Select>
            <Select
              v-model:value="data.key"
              :disabled="isDisable"
              v-if="editData.edit.level === 3"
              placeholder="请选择"
            >
              <SelectOption
                v-for="item in optionLevel3"
                :key="item.value"
                :disabled="isSelectedByOthers(item.value, data.key)"
                >{{ item.label }}</SelectOption
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="10">
          <FormItem :name="[index, 'number']" required>
            <InputNumber
              v-model:value="data.number"
              :disabled="isDisable"
              :min="0"
              :parser="formatNumber"
            />
          </FormItem>
        </Col>
        <Col span="4">
          <FormItem>
            <Button
              size="large"
              shape="circle"
              type="text"
              @click="del(index, data.key)"
              :disabled="isDisable"
            >
              <Icon :icon="ICON.X_DELETE" class="!text-24px" />
            </Button>
          </FormItem>
        </Col>
      </Row>
    </Form>

    <Button
      @click="add"
      v-if="editData.edit.level != 3 && p.length != 2"
      :disabled="isDisable"
      class="!flex items-center"
    >
      <Icon :icon="ICON.PLUS" class="!text-24px" />添加属性</Button
    >
    <Button
      @click="add"
      v-if="editData.edit.level === 3 && p.length != 5"
      :disabled="isDisable"
      class="!flex items-center"
    >
      <Icon :icon="ICON.PLUS" class="!text-24px" />添加属性</Button
    >
  </BasicModal>
</template>

<script lang="ts" setup>
  import {
    Row,
    Col,
    InputNumber,
    Select,
    SelectOption,
    Form,
    FormItem,
    Button,
  } from 'ant-design-vue';
  import { ref, watch } from 'vue';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  const emits = defineEmits(['get-edit']);
  let p = ref<any>([]);
  const pForm = ref<any>({});
  const isDisable = ref<boolean>(false);
  const props = defineProps({
    disable: { type: Boolean },
  });
  //已被选择的属性名称
  let selected = ref<Array<string>>([]);
  let editData = ref<any>({ edit: { level: 1 } });
  let option: Recordable[] = [
    { value: 'pmin', label: '最小周期', disable: false },
    { value: 'pmax', label: '最大周期', disable: false },
  ];
  let optionLevel3 = [
    { value: 'pmin', label: '最小周期', disable: false },
    { value: 'pmax', label: '最大周期', disable: false },
    { value: 'gt', label: '大于', disable: false },
    { value: 'lt', label: '小于', disable: false },
    { value: 'st', label: '步长', disable: false },
  ];
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  const { createMessage } = useMessage();
  const [registerModal, { closeModal }] = useModalInner((data) => {
    editData.value = data;

    p.value = [];
    if (editData.value.edit.level === 1) {
      if (editData.value.pData) p.value = editData.value.pData;
    }
    if (editData.value.edit.level === 2) {
      if (editData.value.instances[editData.value.edit.index].pData)
        p.value = editData.value.instances[editData.value.edit.index].pData;
    }
    if (editData.value.edit.level === 3) {
      if (
        editData.value.instances[editData.value.edit.index].resources[editData.value.edit.index1]
          .pData
      )
        p.value =
          editData.value.instances[editData.value.edit.index].resources[
            editData.value.edit.index1
          ].pData;
    }
  });
  function add() {
    p.value.push({ key: null, number: 0 });
  }
  function del(index: number, keyName: string) {
    selected.value = selected.value.filter((spec) => spec !== keyName);
    p.value.splice(index, 1);
  }
  // 判断range中的值是否被已有的通信配置中选中
  function isSelectedByOthers(optionValue: string, currentSpec: string) {
    return selected.value.includes(optionValue) && optionValue !== currentSpec;
  }
  watch(
    () => p.value,
    (nVal) => {
      selected.value = [];
      nVal.map((item) => {
        selected.value.push(item.key);
      });
    },
    { deep: true },
  );
  async function close() {
    p.value = [];
    selected.value = [];
    editData.value = { edit: { level: 1 } };
    return true;
  }
  function formatNumber(text: string) {
    const decimalIndex = text.indexOf('.');
    return /^\d+$/.test(text) ? text : text.slice(0, decimalIndex);
  }
  async function handleSubmit() {
    let hasEmptyKey = false;
    try {
      await pForm.value.validate();
    } catch (e) {
      hasEmptyKey = true;
    }
    if (hasEmptyKey) {
      createMessage.error('属性名称或属性值不能为空');
      return;
    }
    if (editData.value.edit.level === 1) {
      editData.value.pData = p.value;
    }
    if (editData.value.edit.level === 2) {
      editData.value.instances[editData.value.edit.index].pData = p.value;
    }
    if (editData.value.edit.level === 3) {
      editData.value.instances[editData.value.edit.index].resources[
        editData.value.edit.index1
      ].pData = p.value;
    }

    emits('get-edit', editData.value);
    p.value = [];
    closeModal();
  }
</script>
